package com.zhaojun.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Iterator;
import java.util.Map;

public class HttpServer2 {


    static final String SERVER_CONTEXT="E:/mynetty/netty01/html";
    static final String FILE_UPLOAD="E:/mynetty/netty01/html/upload";


    public static void main(String[] args) {




        NioEventLoopGroup boss=new NioEventLoopGroup();
        NioEventLoopGroup worker=new NioEventLoopGroup();
        ServerBootstrap bootstrap=new ServerBootstrap();
        bootstrap.group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new HttpRequestDecoder())
                                .addLast(new HttpObjectAggregator(1024*1024*50))
                                .addLast(new HttpResponseEncoder())

                                .addLast(new ChunkedWriteHandler())
                                .addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
                                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {

                                        String uri=fullHttpRequest.uri();
                                        HttpHeaders headers = fullHttpRequest.headers();
                                        Iterator<Map.Entry<String, String>> iter = headers.iteratorAsString();
                                        while (iter.hasNext()){
                                            Map.Entry<String, String> entry = iter.next();
                                            System.out.println(entry.getKey()+":"+entry.getValue());
                                        }
                                        if (uri.equals("/index.html")){
                                            byte[] bodyBytes = FileUtils.readFileToByteArray(new File(SERVER_CONTEXT + uri));
                                            DefaultFullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(bodyBytes));
                                            response.headers().add("content-type","text/html;charset=UTF-8");
                                            ChannelFuture f = ctx.writeAndFlush(response);
                                            f.addListener(ChannelFutureListener.CLOSE);
                                        }

                                        if(uri.equals("/file/upload")){

//                                            DefaultHttpDataFactory dataFactory = new DefaultHttpDataFactory(true);
                                            HttpPostMultipartRequestDecoder multipartRequestDecoder=new HttpPostMultipartRequestDecoder(fullHttpRequest);
                                            MixedFileUpload httpData = (MixedFileUpload) multipartRequestDecoder.getBodyHttpData("file");
                                            ByteBuf content = httpData.content();


                                            String fileName=httpData.getFilename();

                                            int byteLen = content.readableBytes();
                                            byte[] fbytes=new byte[byteLen];
                                            content.getBytes(content.readerIndex(),fbytes,0,byteLen);
//                                            System.out.println(new String(fbytes));
                                            FileUtils.writeByteArrayToFile(new File(String.format("%s/%s",FILE_UPLOAD,fileName)),fbytes);
                                        }

                                        DefaultFullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.NOT_FOUND);
                                        response.headers().add("content-type","text/html;charset=UTF-8");
                                        ChannelFuture f = ctx.writeAndFlush(response);
                                        f.addListener(ChannelFutureListener.CLOSE);

                                    }
                                });
                    }
                });


        try {
            ChannelFuture f = bootstrap.bind(8888).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
